package com.cim.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cim.config.GlobalConfig;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * @desc   使用token验证用户是否登录
 * @author zm
 **/
public class TokenUtils {
    //设置过期时间  (30天)
    private static final long EXPIRE_DATE=1000*60*60*24*30L;
    //token秘钥
    private static final String TOKEN_SECRET = GlobalConfig.TOKEN_SECRET;
    public static String token(String username,String password,String role){
        String token="";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim(GlobalConfig.TOKEN_USER,username)
                    .withClaim(GlobalConfig.TOKEN_ROLE,role)
                    .withClaim(GlobalConfig.TOKEN_PASS,password).withExpiresAt(date)
                    .sign(algorithm);
            return token;
        }catch (Exception e){
            return null;
        }
    }


    public static String verify(String token,String key){
        /**
         * @desc   验证token，通过返回true
         * @params [token]需要校验的串
         **/
        if(token==null){
            return null;
        }
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim(key).asString();
        }catch (Exception e){
            return  null;
        }
    }
    public static boolean verify(String token){
        if(token==null||token.equals("")){
            return false;
        }
        return verify(token,GlobalConfig.TOKEN_USER)!=null;
    }
}
